package oer.halk.intercept_demo.intercept;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @Author zhuhao
 * @Date 2022/1/26 14:58
 * @desc
 */
@Component
@Slf4j
public class CustomIntercept implements HandlerInterceptor {

    /**
     * 在业务处理器处理请求之前被调用。
     * 预处理，可以进行编码、安全控制、权限校验等处理；
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //返回站点的根路径
        String contextPath = request.getContextPath();
        log.info("contextPath:  {}", contextPath);

        //请求接口的相对路径
        String servletPath = request.getServletPath();
        log.info("servletPath:  {}", servletPath);

        //获取所有的header
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
//            log.info("header:  {}, value:  {}", headerName, request.getHeader(headerName));
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 在业务处理器处理请求执行完成后，生成视图之前执行
     * 后处理（调用了Service并返回ModelAndView，但未进行页面渲染），有机会修改ModelAndView
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 在DispatcherServlet完全处理完请求后被调用，可用于清理资源等。返回处理（已经渲染了页面）；
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
